<template>
  <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
    <el-tab-pane :label="item.label" :name="item.id" v-for="item in tabsArr" :key="item.id"></el-tab-pane>
    <el-container>
      <el-aside width="280px" class="postList_css">
        <div v-if="activeName == '1'">
          <h3>
            菜单列表
            <el-icon class="icon_css" ref="buttonRef" v-click-outside="onClickOutside"><MoreFilled /></el-icon>
            <el-popover ref="popoverRef" :virtual-ref="buttonRef" trigger="click" title="" virtual-triggering>
              <p class="opt_btn" @click="optClick(1)">选择全部</p>
              <p class="opt_btn" @click="optClick(2)">取消选择</p>
              <p class="opt_btn" @click="optClick(3)">折叠全部</p>
              <p class="opt_btn" @click="optClick(4)">展开全部</p>
            </el-popover>
          </h3>
          <menu-list
            :treeOptType="treeOptType"
            @select-node="selectNode"
            @select-single-data="selectClick"
            @get-tree-data="getTreeData"
          ></menu-list>
        </div>
        <div v-if="activeName == '2'">
          <h3>
            模块列表
            <el-icon class="icon_css" ref="buttonRef" v-click-outside="onClickOutside"><MoreFilled /></el-icon>
            <el-popover ref="popoverRef" :virtual-ref="buttonRef" trigger="click" title="" virtual-triggering>
              <p class="opt_btn" @click="optClick(1)">选择全部</p>
              <p class="opt_btn" @click="optClick(2)">取消选择</p>
              <p class="opt_btn" @click="optClick(3)">折叠全部</p>
              <p class="opt_btn" @click="optClick(4)">展开全部</p>
            </el-popover>
          </h3>
          <model-list
            :treeOptType="treeOptType"
            @select-node="selectNode"
            @select-single-data="selectClick"
          ></model-list>
        </div>
        <div v-if="activeName == '3'">
          <h3>岗位列表</h3>
          <el-input
            :type="'text'"
            v-model="postCname"
            placeholder="请输入"
            @input="onInput"
            @keyup="onInput"
            style="padding: 0 15px 15px 15px"
          >
            <template #suffix>
              <el-icon style="vertical-align: middle">
                <Search @click="getPostList" />
              </el-icon>
            </template>
          </el-input>
          <p
            v-for="(item, index) in postChing(postList, postCname)"
            :key="item.postId"
            :class="postActive == index ? 'postActive_css' : ''"
            @click="selectPostClick(item, index)"
          >
            {{ item.postEname }}-{{ item.postCname }}
          </p>
        </div>
        <div v-if="activeName == '4'">
          <h3>用户组列表</h3>
          <FITree1
            v-if="isShowTree"
            class="tree_box"
            :treeListObj="treeListObj"
            :filter-node-method="filterNode"
            :showFilter="true"
            :showCheckbox="false"
            @nodeClick="nodeClick"
          ></FITree1>
          <!-- <el-input
            class="input_css"
            :type="'text'"
            v-model="groupCname"
            @input="onInput"
            @keyup="onInput"
            placeholder="请输入"
            style="padding: 0 15px 15px 15px"
          >
            <template #suffix>
              <el-icon style="vertical-align: middle">
                <Search @click="getUserList" />
              </el-icon>
            </template>
          </el-input>
          <p
            v-for="(item, index) in usersChing(usersList, groupCname)"
            :key="item.groupId"
            :class="postActive == index ? 'postActive_css' : ''"
            @click="selectPostClick(item, index)"
          >
            {{ item.groupEname }}-{{ item.groupCname }}
          </p> -->
        </div>
        <el-pagination
          v-if="activeName == '3'"
          v-model:current-page="postListPage"
          v-model:page-size="postSize"
          layout="prev, pager,next"
          :total="listTotal"
          :pager-count="5"
          @current-change="handlePostCurrentChange"
          class="post_pagination"
        />
      </el-aside>
      <el-container>
        <el-main>
          <FISearchForm
            v-if="activeName == '1' || activeName == '2'"
            class="box-radius2"
            ref="ruleFormRef"
            :id="`inqu_${tableId}`"
            :searchNum="searchItemCount"
            v-model:form-value="state.query"
            :table-column="columns"
            :wrapperSpan="8"
            @submit="searchFn"
          >
            <el-col :span="8" class="flex-center">
              <FIFormItem prop="subjectType" label="授权主体类型">
                <!-- <FIInput v-model="state.query.subjectType" clearable /> -->
                <FISelect
                  v-model="state.query.subjectType"
                  valueCustom="value"
                  :options="[
                    { value: 'USER_GROUP', label: '用户组' },
                    { value: 'POST', label: '岗位' },
                  ]"
                  clearable
                />
              </FIFormItem>
            </el-col>
            <el-col :span="8" class="flex-center">
              <FIFormItem name="subjectEname" label="授权主体编码">
                <FIInput v-model="state.query.subjectEname" clearable />
              </FIFormItem>
            </el-col>
            <el-col :span="8" class="flex-center">
              <FIFormItem name="subjectCname" label="授权主体名称">
                <FIInput v-model="state.query.subjectCname" clearable />
              </FIFormItem>
            </el-col>
          </FISearchForm>

          <FISearchForm
            v-if="activeName == '3' || activeName == '4'"
            class="box-radius2"
            ref="ruleFormRef"
            :id="`inqu_${tableId}`"
            :searchNum="searchItemCount"
            v-model:form-value="state.query"
            :table-column="columns"
            :wrapperSpan="8"
            @submit="searchFn"
          >
            <el-col :span="8" class="flex-center">
              <FIFormItem prop="resourceType" label="资源类型">
                <FISelect
                  v-model="state.query.resourceType"
                  valueCustom="value"
                  :options="[
                    { value: 'PAGE', label: '页面' },
                    { value: 'BUTTON', label: '按钮' },
                  ]"
                  clearable
                />
              </FIFormItem>
            </el-col>
            <el-col :span="8" class="flex-center">
              <FIFormItem name="resourceEname" label="资源编码">
                <FIInput v-model="state.query.resourceEname" clearable />
              </FIFormItem>
            </el-col>
            <el-col :span="8" class="flex-center">
              <FIFormItem name="resourceCname" label="资源名称">
                <FIInput v-model="state.query.resourceCname" clearable />
              </FIFormItem>
            </el-col>
          </FISearchForm>
          <div class="margin-bottom20"></div>

          <FITable
            ref="tableRef"
            class="box-radius2"
            title="授权列表"
            :id="`result_${tableId}`"
            :readonly="false"
            :data="state.dataList"
            :insertable="false"
            deletable
            primaryKey="formId"
            v-model:columns="columns"
            :isLoading="isTableLoading"
            :saveSuccessful="saveSuccessful"
            :pageConfig="pageConfig"
            @table-refresh="searchFn"
            @selection-change="handleSelectionChange"
            @size-change="handleSizeChange"
            @current-page-change="handleCurrentChange"
            @row-delete="deleteRow"
          >
            <template #headerBtn>
              <div v-if="activeName == '1' || activeName == '2'">
                <FIButton id="openPost" border class="margin-left5" @click.stop="btnClick('post')"></FIButton>
                <FIButton id="openUserGroup" border class="margin-left5" @click.stop="btnClick('users')"></FIButton>
              </div>
              <div v-if="activeName == '3' || activeName == '4'">
                <FIButton id="openMenuTree" border class="margin-left5" @click.stop="btnClick('menu')"></FIButton>
                <FIButton id="openModuleTree" border class="margin-left5" @click.stop="btnClick('model')"></FIButton>
              </div>
              <!-- <FIPopconfirmBtn
							class="margin-left5"
							title="您是否确认删除选中数据吗？"
							buttonText="删除"
							beforePopText="请选择一条数据"
							:btn-binds="{ id: 'delete', border: true }"
							:isVisible="!!checkedRows.length"
							@confirm="deleteRow"
						>
						</FIPopconfirmBtn> -->
            </template>
          </FITable>
        </el-main>
      </el-container>
    </el-container>
  </el-tabs>
  <selectUsers
    :usersShow="usersShow"
    @update:usersShow="(newValue) => (usersShow = newValue)"
    :treeVal="treeVal"
    :activeName="activeName"
    @post-close="postCloseQuery"
  ></selectUsers>
  <selectPost
    :postShow="postShow"
    @update:postShow="(newValue) => (postShow = newValue)"
    :treeVal="treeVal"
    :activeName="activeName"
    @post-close="postCloseQuery"
  ></selectPost>
  <!-- <model-tree :modelShow="modelShow" @update:modelShow="(newValue) => (modelShow = newValue)" :editData="editData"></model-tree> -->
  <!-- <menu-tree :menuShow="menuShow" @update:menuShow="(newValue) => (menuShow = newValue)"></menu-tree> -->
  <FIModel v-model="menuShow" width="700" title="菜单树授权" @close="menuShow = false" @confirm="saveMenuFunc">
    <el-row :gutter="20">
      <el-col>
        <p class="shouq_title">
          <span class="label_css">{{ activeName == '3' ? '岗位名称' : '用户组名称' }}</span>
          <span v-if="activeName == '3'">{{ editData.postEname }} - {{ editData.postCname }}</span>
          <span v-else>{{ editData.groupEname }} - {{ editData.groupCname }}</span>

          <el-button class="btn" @click="copyAuth">复制权限</el-button>
        </p>
      </el-col>
    </el-row>
    <FIFormItem prop="formEname" label="菜单树列表">
      <menu-list
        @select-node="selectNode"
        :copy-auth="treeDataList"
        style="width: 400px; height: 600px; overflow: auto"
        @close-drawer="closeDrawer"
        :drawer="drawer"
        :buttonPage_Ckeck="true"
      ></menu-list>
    </FIFormItem>
  </FIModel>
  <FIModel v-model="modelShow" width="700" title="模块树授权" @close="modelShow = false" @confirm="saveMenuFunc">
    <el-row :gutter="20">
      <el-col>
        <p class="shouq_title">
          <span class="label_css">{{ activeName == '3' ? '岗位名称' : '用户组名称' }}</span>
          <span v-if="activeName == '4'">{{ editData.groupEname }} - {{ editData.groupCname }}</span>
          <span v-else>{{ editData.postEname }} - {{ editData.postCname }}</span>
          <el-button class="btn" @click="copyAuth">复制权限</el-button>
        </p>
      </el-col>
      <el-col :span="24">
        <FIFormItem prop="formEname" label="模块树列表">
          <model-list
            @select-node="selectNode"
            :copy-auth="treeDataList"
            style="width: 400px; height: 600px; overflow: auto"
            @close-drawer="closeDrawer"
            :drawer="drawer"
            :buttonPage_Ckeck="true"
          ></model-list>
        </FIFormItem>
      </el-col>
    </el-row>
  </FIModel>
  <el-drawer v-model="drawer" :direction="direction" :modal="true" :append-to-body="true" modal-class="mask-layer">
    <template #header>
      <h4>复制权限</h4>
    </template>
    <template #default>
      <div v-if="activeName == '3'">
        <FIFormItem prop="postEname" label="岗位编码或名称">
          <el-input
            class="input_css"
            :type="'text'"
            v-model="postObj.postAName"
            @input="ondrawerInput"
            @keyup="ondrawerInput"
            placeholder="请输入"
          >
            <template #suffix>
              <el-icon style="vertical-align: middle">
                <Search @click="postSearch" />
              </el-icon>
            </template>
          </el-input>
          <!-- <FIInput v-model="state.query.postEname" clearable /> -->
        </FIFormItem>
        <!-- <FIFormItem prop="postCname" label="岗位名称">
				<el-input
					class="input_css"
					:type="'text'"
					v-model="postObj.postCname"
					placeholder="请输入">
					<template #suffix>
					<el-icon style="vertical-align: middle">
						<Search @click="postSearch"/>
					</el-icon>
					</template>
				</el-input>
			</FIFormItem> -->
        <el-table ref="multipleTableRef" :data="postDrawer" style="width: 100%">
          <el-table-column label="" width="50">
            <template v-slot="scope">
              <el-radio :label="scope.row.postId" v-model="selectedId" @change="handleRadioChange(scope.row)">
              </el-radio>
            </template>
          </el-table-column>
          <el-table-column prop="postEname" label="岗位编码" algin="center" />
          <el-table-column prop="postCname" label="岗位名称" algin="center" />
        </el-table>
      </div>
      <div v-if="activeName == '4'">
        <FIFormItem prop="groupEname" label="用户组编码或名称">
          <el-input
            class="input_css"
            :type="'text'"
            v-model="usersObj.groupAName"
            @input="ondrawerInput"
            @keyup="ondrawerInput"
            placeholder="请输入"
          >
            <template #suffix>
              <el-icon style="vertical-align: middle">
                <Search @click="usersSearch" />
              </el-icon>
            </template>
          </el-input>
        </FIFormItem>
        <!-- <FIFormItem prop="groupCname" label="用户组名称">
				<el-input
					class="input_css"
					:type="'text'"
					v-model="usersObj.groupCname"
					placeholder="请输入">
					<template #suffix>
					<el-icon style="vertical-align: middle">
						<Search @click="usersSearch"/>
					</el-icon>
					</template>
				</el-input>
			</FIFormItem> -->
        <el-table ref="multipleTableRef" :data="usersDrawer" style="width: 100%">
          <el-table-column label="" width="50">
            <template v-slot="scope">
              <el-radio :label="scope.row.groupId" v-model="selectedId" @change="handleRadioChange(scope.row)">
              </el-radio>
            </template>
          </el-table-column>
          <el-table-column prop="groupEname" label="用户组编码" algin="center" />
          <el-table-column prop="groupCname" label="用户组名称" algin="center" />
        </el-table>
      </div>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick" style="float: right; margin-left: 10px">取消</el-button>
        <FIPopconfirmBtn
          title="你确定要复制权限吗？"
          buttonText="复制权限"
          beforePopText="请选择一条数据"
          :btn-binds="{ customType: 'border', border: true }"
          :isVisible="!!selectedId"
          @confirm="confirmClick"
        >
        </FIPopconfirmBtn>
      </div>
    </template>
  </el-drawer>
</template>
<script lang="ts" setup>
import { onMounted, ref, reactive, computed, toRaw, unref } from 'vue'
import type { TabsPaneContext } from 'element-plus'
import {
  apiGetDeptTree,
  apiAuthMaintquery,
  apiPostquery,
  apiGroupMaintquery,
  apiSaveAuthoritys,
  apiGetXslvDeptTree,
  apiAuthMaintdelete,
  apiAuthdeleteBySubject,
  apiAuthorityQueryAll,
} from '@/api/user'
import { initSearchData } from '@/utils/common'
import { useMessage } from '@/hooks/message'
import selectUsers from './components/selectUsers'
import selectPost from './components/selectPost'
import menuList from './components/menuList'
import modelList from './components/modelList'
import type { PageConfig, Column } from '@/types/components'
import type { DrawerProps } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { apiRequestPost } from '@/api/globalApi.js'
import { MoreFilled } from '@element-plus/icons-vue'
import { ClickOutside as vClickOutside } from 'element-plus'
import { getCurrentInstance } from 'vue'
import { useRoute } from 'vue-router'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
const buttonRef = ref()
const popoverRef = ref()
const route = useRoute()
const onClickOutside = () => {
  unref(popoverRef).popperRef?.delayHide?.()
}
const drawer = ref(false)
const direction = ref<DrawerProps['direction']>('rtl')
const tabsArr = ref([
  {
    label: '菜单视角授权',
    id: '1',
  },
  {
    label: '模块视角授权',
    id: '2',
  },
  {
    label: '岗位视角授权',
    id: '3',
  },
  {
    label: '用户组视角授权',
    id: '4',
  },
])
const listTotal = ref(0)
// const valueShow = ref(false)
const modelShow = ref(false)
const menuShow = ref(false)
const usersShow = ref(false)
const postShow = ref(false)
const orgVisible = ref(false)
const isTableLoading = ref(false)
// 页面编码
const tableId = 'authManage'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)
const modelValue = ref(false)
const treeList = ref([])
const postList = ref([])
const usersList = ref([])
const rawArray = ref([])
const postListPage = ref(1)
const postEname = ref('')
const postActive = ref(0)
const postSize = ref(15)
const editData = ref({})
const treeVal = ref([])
const treeObj = ref({})
const menuTreeData = ref([])
const selectedId = ref('')
const buttonType = ref(1)
const postObj = ref({})
const usersObj = ref({})
const postDrawer = ref([])
const usersDrawer = ref([])
const treeOptType = ref(0)
const postCname = ref('')
const groupCname = ref('')
const subjectId = ref('')
const treeListObj = ref({})
const treeDataList = ref([]) //回显树里面的数据
// const authUserPost = ref({})
const copyAuth = () => {
  drawer.value = true
  selectedId.value = ''
  if (activeName.value == '3') {
    postObj.value = {}
    getPostDrawer()
  }
  if (activeName.value == '4') {
    usersObj.value = {}
    getUserDrawer()
  }
}
const postSearch = () => {
  getPostDrawer()
}
const usersSearch = () => {
  getUserDrawer()
}
const cancelClick = () => {
  drawer.value = false
}
const closeDrawer = (data) => {
  treeVal.value = data
  console.log(treeVal, 'chakan-----treeVal')
}
const confirmClick = () => {
  if (!selectedId.value) {
    useMessage().warning('请选择一条数据')
    return
  }
  drawer.value = false
}
const optClick = (type) => {
  treeOptType.value = type
}
const handleRadioChange = (val) => {
  // authUserPost.value = val
  activeName.value == '3' ? (selectedId.value = val.postId) : (selectedId.value = val.groupId)
  searchFn('query', '')
  // const par = {
  // 	subjectId:subjectId || '',
  // 	...state.query,
  // 	resourceType,
  // 	// resourceEname,
  // 	// resourceCname,
  // 	resourceId
  // }
  // apiAuthMaintquery(par)
  // .then((res) => {
  // 	isTableLoading.value = false
  // 	if (res.data.success) {
  // 	state.dataList = res.data.data.result
  // 	pageConfig.pageSize = Number(res.data.data.size)
  // 	pageConfig.total = Number(res.data.data.count)
  // 	} else {
  // 	// ElMessage.error(res.data.message)
  // 	}
  // })
  // .catch((error: any) => {
  // 	isTableLoading.value = false
  // 	// 处理错误
  // })
}
const btnClick = (type) => {
  if (type == 'post') {
    if (!treeVal.value.length) {
      useMessage().warning('请选菜单数据')
      return
    }
    postShow.value = true
  }
  if (type == 'users') {
    if (!treeVal.value.length) {
      useMessage().warning('请选菜单数据')
      return
    }
    usersShow.value = true
  }
  if (type == 'menu') {
    buttonType.value = 1
    menuShow.value = true
  }
  if (type == 'model') {
    buttonType.value = 2
    modelShow.value = true
  }
}
const getTreeData = (data) => {
  menuTreeData.value = data
}
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.label.includes(value)
}
const nodeClick = (val) => {
  console.log(val,'val123')
  // treeObj.value = val
  subjectId.value = val.value
  // state.query.deptEname = val.orgEname,
  searchFn('query', '')
}
const saveMenuFunc = () => {
  console.log(treeVal, 'treeVal')
  let list = treeVal.value.map((v) => {
    if (v.payload.resourceId) {
      return {
        resourceId: v.payload.resourceId,
        resourceType: v.payload.resourceType,
      }
    }
  })
  console.log(list, '查看list')
  console.log(selectedId, 'selectedId123')
  let par = {
    authorityList: list.filter((item) => item !== undefined),
    // subjectId:activeName.value == '3' ? editData.value.postId : editData.value.groupId,
    subjectId: selectedId.value
      ? selectedId.value
      : activeName.value == '3'
      ? editData.value.postId
      : subjectId.value,
    subjectType: activeName.value == '4' ? 'USER_GROUP' : 'POST',
  }
  apiSaveAuthoritys(par)
    .then((res) => {
      if (res.data.success) {
        useMessage().success(res.data.message)

        menuShow.value = false
        modelShow.value = false

        drawer.value = false
        searchFn('query', '')
      }
    })
    .catch((error: any) => {})
}

//删除事件
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  isTableLoading.value = true
  const arr = checkedRows.value.map((v) => {
    return {
      resourceId: v.resourceId,
      resourceType: v.resourceType,
      subjectId: v.subjectId,
      subjectType: v.subjectType,
    }
  })
  const apiUrl = proxy.$Button_api('delete', route.name)
  apiRequestPost(apiUrl, arr)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success(res.data.message)
        searchFn('query', '')
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // useMessage().error(error.data.message)
    })
}
const state = reactive({
  query: {
    subjectType: '',
    subjectEname: '',
    subjectCname: '',
    resourceType: '',
    resourceEname: '',
    resourceCname: '',
    current: 1,
    size: 10,
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const selectNode = (data) => {
  treeVal.value = data

  // searchFn('query','',data.payload.nodeId)
}
const selectClick = (data) => {
  console.log(data, 'data777')
  treeObj.value = data.payload
  if (!data.payload.resourceId) {
    state.dataList = []
    return
  }
  if (!data.payload.resourceEname) {
    state.dataList = []
    return
  }
  searchFn('query', '')
}
const postCloseQuery = () => {
  console.log(treeObj.value, 'ppp')
  if (!treeObj.value.resourceId) return
  if (!treeObj.value.resourceEname) return
  searchFn('query', '')
}
const columns: Column[] = reactive([
  {
    label: '授权主体编码',
    prop: 'subjectEname',
    align: 'center',
    // editable: false,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '授权主体名称',
    prop: 'subjectCname',
    align: 'center',
    queryName: '',
    editable: true,
    sortable: false,
    filterable: false,
    readonly: true,
    editType: 'input',
  },
  {
    label: '资源编码',
    prop: 'resourceEname',
    queryName: 'tedfa00.form_Cname',
    align: 'center',
    editType: 'input',
    editable: true,
    filterable: false,
    sortable: false,
    sortValue: '',
  },
  {
    label: '资源名称',
    prop: 'resourceCname',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editable: true,
    filterable: false,
    modelValue: { inputValue: '' },
    sortable: false,
    sortValue: '',
  },
  {
    label: '创建人',
    prop: 'recCreator',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '创建时间',
    prop: 'recCreateTime',
    align: 'center',
    editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改人',
    prop: 'recRevisor',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改时间',
    prop: 'recReviseTime',
    align: 'center',
    editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
])

const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const activeName = ref('1')
const handleClick = (tab: TabsPaneContext, event: Event) => {
  postListPage.value = 1
  pageConfig.currentPage = 1
  treeObj.value = {}
  if (tab.props.name == '1' || tab.props.name == '2') {
    state.dataList = []
  } else if (tab.props.name == '3') {
    postActive.value = 0
    state.query.subjectType = 'POST'

    getPostList()
  } else if (tab.props.name == '4') {
    console.log(toRaw(editData), 'editData------------')
    postActive.value = 0
    state.query.subjectType = 'USER_GROUP'
    // getUserList()
    getTreeListGroup()
  }
}
const getTreeList = async () => {
  const { data } = await apiGetDeptTree()
  if (data.success) {
    treeList.value = data.data.subNodes
  }
}
const selectPostClick = (item, index) => {
  editData.value = item
  postActive.value = index
  pageConfig.currentPage = 1
  console.log(activeName.value, 'activeName.value')
  searchFn('query', '')
  getCopyTree()
}
const getCopyTree = () => {
  const { resourceId } = treeObj.value
  const par = {
    subjectId: activeName.value == '3' ? editData.value.postId : editData.value.groupId,
    ...state.query,
    // resourceEname,
    // resourceCname,
    resourceId,
  }
  delete par.size
  apiAuthorityQueryAll(par)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        treeDataList.value = res.data.data
        // pageConfig.pageSize = Number(res.data.data.size)
        // pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns

  if(type == 'page'){
    state.query.current = pageConfig.currentPage
  }else{
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const { resourceType, resourceCname, resourceEname, resourceId } = treeObj.value
  const par = {
    subjectId: activeName.value == '3' ? editData.value.postId : subjectId.value,
    ...state.query,
    // resourceEname,
    // resourceCname,
    resourceId,
  }
  const apiUrl = proxy.$Button_api('query', route.name)
  apiRequestPost(apiUrl, par)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn('query', '')
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page', '')
}
const handlePostCurrentChange = (e) => {
  postListPage.value = e
  if (activeName.value == '3') {
    getPostList()
  } else {
    getUserList()
  }
}
// 隐藏搜索项有值的个数
const searchItemCount = computed(() => {
  let filledCount = 0
  const outKeys = ['dynamicParams', 'orderbyParams', 'size', 'current']
  // 下面是从第三项起计算常规搜索条件有值个树
  // 获取state.query的所有keys
  const queryKeys = Object.keys(state.query).filter((key) => !outKeys.includes(key))
  if (queryKeys.length < 3) return 0
  // 从第三项开始计算
  queryKeys.slice(2).forEach((key) => {
    if (state.query[key] !== '' && state.query[key] !== null) {
      filledCount++
    }
  })
  return filledCount
})
const getTreeListGroup = async() => {
  
  const {data} = await apiGetXslvDeptTree({scene:4})
  if(data.success){
      // dataList.value = data.data.subNodes
      treeListObj.value = data.data;
      isShowTree.value = true
      console.log(treeListObj.value,'调用了')
  }
}
const isShowTree = ref(false)
const postChing = (list, input) => {
  if (!input) return list
  return list.filter((item) => {
    if (item.postCname.indexOf(input) != -1 || item.postEname.indexOf(input) != -1) {
      return item
    }
  })
}
const usersChing = (list, input) => {
  if (!input) return list
  return list.filter((item) => {
    if (item.groupCname.indexOf(input) != -1 || item.groupEname.indexOf(input) != -1) {
      return item
    }
  })
}
//获取岗位列表
const getPostList = () => {
  const par = {
    current: postListPage.value,
    size: postSize.value,
    // postCname:postCname.value,
    postAName: postCname.value,
  }
  apiPostquery(par)
    .then((res) => {
      if (res.data.success) {
        postList.value = res.data.data.result
        //   pageConfig.pageSize = Number(res.data.data.size)
        listTotal.value = Number(res.data.data.count)
        editData.value = postList.value[0]
        console.log(editData, 'editData')
        searchFn('query', '')
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      // 处理错误
    })
}
//获取岗位列表--用于弹出右边岗位列表
const getPostDrawer = () => {
  const par = {
    current: postListPage.value,
    size: postSize.value,
    // postCname:postObj.value.postCname,
    // postEname:postObj.value.postEname,
    postAName: postObj.value.postAName,
  }
  apiPostquery(par)
    .then((res) => {
      if (res.data.success) {
        postDrawer.value = res.data.data.result
        //   pageConfig.pageSize = Number(res.data.data.size)
        listTotal.value = Number(res.data.data.count)
      }
    })
    .catch((error: any) => {
      // 处理错误
    })
}

let timers = null
// 防抖 input改变
const onInput = () => {
  clearTimeout(timers)
  timers = setTimeout(() => {
    activeName.value == '3' ? getPostList() : getUserList()
  }, 800) //多久时间内执行一次
}
let drawerTimers = null
// 防抖 input改变
const ondrawerInput = () => {
  clearTimeout(drawerTimers)
  drawerTimers = setTimeout(() => {
    activeName.value == '3' ? postSearch() : usersSearch()
  }, 800) //多久时间内执行一次
}

const getUserList = () => {
  const par = {
    current: postListPage.value,
    size: postSize.value,
    groupCname: groupCname.value,
    groupAName: groupCname.value,
  }
  apiGroupMaintquery(par)
    .then((res) => {
      if (res.data.success) {
        usersList.value = res.data.data.result
        //   pageConfig.pageSize = Number(res.data.data.size)
        listTotal.value = Number(res.data.data.count)
        editData.value = usersList.value[0]
        searchFn('query', '')
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      // 处理错误
    })
}
//获取岗位列表--用于弹出右边岗位列表
const getUserDrawer = () => {
  const par = {
    current: postListPage.value,
    size: postSize.value,
    // groupCname:usersObj.value.groupCname,
    // groupEname:usersObj.value.groupEname,
    groupAName: usersObj.value.groupAName,
  }
  apiGroupMaintquery(par)
    .then((res) => {
      if (res.data.success) {
        usersDrawer.value = res.data.data.result
        //   pageConfig.pageSize = Number(res.data.data.size)
        //   listTotal.value = Number(res.data.data.count)
        //   editData.value = usersList.value[0]
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      // 处理错误
    })
}

onMounted(() => {
  getTreeList()
  // searchFn()
  // getPostList()
})
</script>
<style lang="less" scoped>
/deep/ .el-radio__label {
  display: none;
}
/deep/ .mask-layer {
  width: 264px !important;
}
/deep/ .el-main {
  padding-top: 0;
}
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
.opt_btn {
  line-height: 30px;
  text-align: center;
  cursor: pointer;
}
.postList_css {
  background: #fff;
  position: relative;
  height: calc(100vh - 200px);
  h3 {
    font-size: 18px;
    line-height: 55px;
    padding-left: 15px;
    border-bottom: 1px solid #eee;
    margin-bottom: 20px;
    color: #000000;
    .icon_css {
      float: right;
      margin-top: 16px;
      margin-right: 12px;
    }
  }

  .input-css {
    padding: 0px 15px 20px 15px;
  }
  p {
    line-height: 35px;
    padding: 0px 8px;
    margin: 0 15px;
    cursor: pointer;
  }
  .postActive_css {
    background: #fff3f3;
    color: #b5415a;
  }
  .post_pagination {
    // width:240px;
    position: absolute;
    bottom: 20px;
    right: 10px;
  }
}
.shouq_title {
  line-height: 50px;
  margin-bottom: 20px;
  border-bottom: 0.5px solid #eee;
  .label_css {
    margin-right: 20px;
    font-size: 16px;
    font-weight: bold;
    color: #000000;
  }
  .btn {
    float: right;
  }
}
</style>
